package com.liyunc.socket.webclient.util;

import com.liyunc.socket.webclient.logger.Logger;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/*
  HTTP Response = Status-Line
    *(( general-header | response-header | entity-header ) CRLF)
    CRLF
    [ message-body ]
    Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
*/
public class Response {

    private final StringBuilder headInfo;//响应头
    private final StringBuilder content;//响应内容
    private int length;//响应长度
    private OutputStream output;

    private static final int CAPACITY = 2048;
    private static final String CRLF = "\r\n";

    public Response() {
        headInfo = new StringBuilder(CAPACITY);
        content = new StringBuilder(CAPACITY);
    }

    public Response(OutputStream output) {
        this();
        this.output = output;
    }

    public void send(int code, String info) {
        content.append(info);
        length = info.length();
        this.createHeaderInfo(code);
        this.push();
    }

    public void createHeaderInfo(int code) {
        headInfo.append("HTTP/1.1 ").append(code).append(CRLF);
        headInfo.append("Content-Type: text/html;charset=utf-8").append(CRLF);
        headInfo.append("Content-Length: ").append(length).append(CRLF);
        headInfo.append(CRLF);
    }

    private void push() {
        try {
            String message = headInfo.toString() + content.toString();
            Logger.info("//message: " + content.toString());
            output.write(message.getBytes(StandardCharsets.UTF_8));
            output.flush();
            output.close();
        } catch (IOException e) {
            Logger.error(e.toString());
        }
    }
}
